package com.ym.util;

import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {

	private static final Log logger = LogFactory.getLog(JsonUtil.class);
	public static ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * Object转换json字符串
	 * 
	 * @param obj
	 *            需要转换的数据
	 */
	public static String obj2Json(Object obj) {
		return obj2Json(obj, false, null);
	}

	/**
	 * Object转换json字符串
	 * 
	 * @param obj
	 *            需要转换的数据
	 * @param dateFormat
	 *            日期格式化 默认：timestamp
	 */
	public static String obj2Json(Object obj, String dateFormat) {
		return obj2Json(obj, false, dateFormat);
	}

	/**
	 * Object转换json字符串 带格式化
	 * 
	 * @param obj
	 *            需要转换的数据
	 * @param isJsonFormat
	 *            json数据是否格式化
	 * @param dateFormat
	 *            日期格式化 默认：timestamp
	 */
	public static String obj2Json(Object obj, boolean isJsonFormat, String dateFormat) {
		String str = null;
		try {
			JsonFactory jf = new JsonFactory();
			StringWriter sw = new StringWriter();
			JsonGenerator jg = jf.createGenerator(sw);
			if (isJsonFormat) // json数据是否格式化
				jg.useDefaultPrettyPrinter();
			if (StringUtils.hasText(dateFormat)) // 日期格式化
				objectMapper.setDateFormat(new SimpleDateFormat(dateFormat));
			objectMapper.writeValue(jg, obj);
			str = sw.toString();
		} catch (Exception e) {
			logger.debug(e.getMessage());
		}
		return str;
	}

	/**
	 * json转换Map字符串 带格式化
	 * 
	 * @param json
	 *            需要转换的数据
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> json2Map(String json) {
		Map<String, Object> res = new HashMap<>();
		try {
			res = objectMapper.readValue(json, HashMap.class);
		} catch (IOException e) {
			logger.debug(e.getMessage());
		}
		return res;
	}

}
